import loginReq from "../vo/loginReq.ts";
import {ElMessage, FormInstance} from "element-plus";
import loginService from "../service/loginService.ts";
import router from "../../../router";
import {encode} from "js-base64";
import {ref, reactive, defineComponent, getCurrentInstance} from 'vue'
//import { useUserStore } from '../../../store/index';
export default defineComponent({
    name: 'Login',
    components: {},
    props: {},
    emits: [],
    setup(props, {emit}) {
        // 获取当前实例
        const {proxy, appContext} = getCurrentInstance()!;

        // 登录service
        const service = new loginService();



        //from表单校验
        const ruleFormRef = ref<FormInstance>();
        // 这里存放数据
        const user = reactive<loginReq>(new loginReq());

        const users = reactive<loginReq>({
            account: '',
            password: '',
            verifyCode: ''
        })
        //校验
        const validatePassword = (rule: any, value: any, callback: any) => {
            if (value === '') {
                callback(new Error('请输入密码'))
            } else {
                callback()
            }
        }
        const validateAccount = (rule: any, value: any, callback: any) => {
            if (value === '') {
                callback(new Error('请输入账号'))
            } else {
                callback()
            }
        }
        const validateVerification = (rule: any, value: any, callback: any) => {
            if (value === '') {
                callback(new Error('请输入验证码'))
            } else {
                callback()
            }
        }
        //校验
        const rules = reactive({
            password: [{validator: validatePassword, trigger: 'blur'}],
            account: [{validator: validateAccount, trigger: 'blur'}],
            verifyCode: [{validator: validateVerification, trigger: 'blur'}],
        })
        const changeRegist = () => {
            router.replace('/regist')
        }
        let imgUrl = ref("http://localhost:8080/api/login/verifyCode?time=" + new Date());
        const resetImg = () => {
            imgUrl.value = "http://localhost:8080/api/login/verifyCode?time=" + new Date();
        }

        const onSubmit = (formEl: FormInstance | undefined) => {
            if (!formEl) return
            formEl.validate((valid) => {
                if (valid) {
                    Object.keys(user).forEach((key) => {
                        if (key == 'account' || key == 'password') {
                            users[key] = encode(user[key])
                        } else {
                            users[key] = user[key]
                        }
                    })
                    service.login(users).then((res: any) => {
                        if (res.data.code == '200') {
                            ElMessage({
                                message: '登录成功',
                                type: 'success'
                            })
                            localStorage.setItem('userInfo', JSON.stringify(res.data.data.userInfo));
                            localStorage.setItem('token', res.data.data.token);
                            // 2. 跳转到  elem 后台！！！
                            router.push('/home')
                        } else {
                            ElMessage.error("账号或密码错误！")
                        }
                    }).catch(error => {
                        console.log(error)
                        ElMessage.error("账号或密码错误！")
                    })
                } else {
                    ElMessage.error("错误的提交！")
                    return false
                }
            })
        }
        const options = {
            fpsLimit: 60,
            interactivity: {
                detectsOn: 'canvas',
                events: {
                    onClick: { // 开启鼠标点击的效果
                        enable: true,
                        mode: 'push'
                    },
                    onHover: { // 开启鼠标悬浮的效果(线条跟着鼠标移动)
                        enable: true,
                        mode: 'grab'
                    },
                    resize: true
                },
                modes: { // 配置动画效果
                    bubble: {
                        distance: 400,
                        duration: 2,
                        opacity: 0.8,
                        size: 40
                    },
                    push: {
                        quantity: 4
                    },
                    grab: {
                        distance: 200,
                        duration: 0.4
                    },
                    attract: { // 鼠标悬浮时，集中于一点，鼠标移开时释放产生涟漪效果
                        distance: 200,
                        duration: 0.4,
                        factor: 5
                    }
                }
            },
            particles: {
                color: {
                    value: '#BA55D3' // 粒子点的颜色
                },
                links: {
                    color: '#FFBBFF', // 线条颜色
                    distance: 150,//线条距离
                    enable: true,
                    opacity: 0.4, // 不透明度
                    width: 1.2 // 线条宽度
                },
                collisions: {
                    enable: true
                },
                move: {
                    attract: {enable: false, rotateX: 600, rotateY: 1200},
                    bounce: false,
                    direction: 'none',
                    enable: true,
                    out_mode: 'out',
                    random: false,
                    speed: 0.5, // 移动速度
                    straight: false
                },
                number: {
                    density: {
                        enable: true,
                        value_area: 800
                    },
                    value: 80//粒子数
                },
                opacity: {//粒子透明度
                    value: 0.7
                },
                shape: {//粒子样式
                    type: 'star'
                },
                size: {//粒子大小
                    random: true,
                    value: 3
                }
            },
            detectRetina: true
        }

        return {
            options,
            user,
            users,
            rules,
            imgUrl,
            resetImg,
            onSubmit,
            changeRegist,
            ruleFormRef
        }
    }
})